<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MultipartFile | YiChangKong For Blog</title><meta name="keywords" content="技术"><meta name="author" content="伊长空"><meta name="copyright" content="伊长空"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><meta name="description" content="MultipartFile类（Spring框架） 起源 ： 在学习一个商城的web应用时，发现UpdateFile的控制器内部使用的就是这个技术类。  1. 配置文件SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver用于处理表单中的file 1234567&lt;!-- 配置MultipartResolver 用于文件上传">
<meta property="og:type" content="article">
<meta property="og:title" content="MultipartFile">
<meta property="og:url" content="https://yichangkong.gitee.io/2019/10/22/MultipartFile/index.html">
<meta property="og:site_name" content="YiChangKong For Blog">
<meta property="og:description" content="MultipartFile类（Spring框架） 起源 ： 在学习一个商城的web应用时，发现UpdateFile的控制器内部使用的就是这个技术类。  1. 配置文件SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver用于处理表单中的file 1234567&lt;!-- 配置MultipartResolver 用于文件上传">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg">
<meta property="article:published_time" content="2019-10-22T08:34:58.000Z">
<meta property="article:modified_time" content="2022-04-28T16:20:52.202Z">
<meta property="article:author" content="伊长空">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://yichangkong.gitee.io/2019/10/22/MultipartFile/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  ClickShowText: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  justifiedGallery: {
    js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
    css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
};

var saveToLocal = {
  set: function setWithExpiry(key, value, ttl) {
    const now = new Date()
    const expiryDay = ttl * 86400000
    const item = {
      value: value,
      expiry: now.getTime() + expiryDay,
    }
    localStorage.setItem(key, JSON.stringify(item))
  },

  get: function getWithExpiry(key) {
    const itemStr = localStorage.getItem(key)

    if (!itemStr) {
      return undefined
    }
    const item = JSON.parse(itemStr)
    const now = new Date()

    if (now.getTime() > item.expiry) {
      localStorage.removeItem(key)
      return undefined
    }
    return item.value
  }
}</script><script id="config_change">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-29 00:20:52'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(function () {  window.activateDarkMode = function () {
    document.documentElement.setAttribute('data-theme', 'dark')
    if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
    }
  }
  window.activateLightMode = function () {
    document.documentElement.setAttribute('data-theme', 'light')
   if (document.querySelector('meta[name="theme-color"]') !== null) {
      document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
    }
  }
  const autoChangeMode = 'false'
  const t = saveToLocal.get('theme')
  if (autoChangeMode === '1') {
    const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
    const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
    const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
    const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified
    if (t === undefined) {
      if (isLightMode) activateLightMode()
      else if (isDarkMode) activateDarkMode()
      else if (isNotSpecified || hasNoSupport) {
        const now = new Date()
        const hour = now.getHours()
        const isNight = hour <= 6 || hour >= 18
        isNight ? activateDarkMode() : activateLightMode()
      }
      window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
        if (saveToLocal.get('theme') === undefined) {
          e.matches ? activateDarkMode() : activateLightMode()
        }
      })
    } else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else if (autoChangeMode === '2') {
    const now = new Date()
    const hour = now.getHours()
    const isNight = hour <= 6 || hour >= 18
    if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
    else if (t === 'light') activateLightMode()
    else activateDarkMode()
  } else {
    if (t === 'dark') activateDarkMode()
    else if (t === 'light') activateLightMode()
  }const asideStatus = saveToLocal.get('aside-status')
if (asideStatus !== undefined) {
   if (asideStatus === 'hide') {
     document.documentElement.classList.add('hide-aside')
   } else {
     document.documentElement.classList.remove('hide-aside')
   }
}})()</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20200417183933.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">9</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">45</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg)"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">YiChangKong For Blog</a></span><span id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> Home</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> Archives</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> Tags</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> Categories</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><span class="close" id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></span></span></nav><div id="post-info"><h1 class="post-title">MultipartFile</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-10-22T08:34:58.000Z" title="发表于 2019-10-22 16:34:58">2019-10-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-28T16:20:52.202Z" title="更新于 2022-04-29 00:20:52">2022-04-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/MultipartFile/">MultipartFile</a></span></div><div class="meta-secondline"> <span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="MultipartFile类（Spring框架）"><a href="#MultipartFile类（Spring框架）" class="headerlink" title="MultipartFile类（Spring框架）"></a>MultipartFile类（Spring框架）</h3><blockquote>
<p>起源 ： 在学习一个商城的web应用时，发现UpdateFile的控制器内部使用的就是这个技术类。</p>
</blockquote>
<h3 id="1-配置文件"><a href="#1-配置文件" class="headerlink" title="1. 配置文件"></a>1. 配置文件</h3><p>SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver用于处理表单中的file</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver --&gt;</span><br><span class="line">  &lt;beans:bean id&#x3D;&quot;multipartResolver&quot; class&#x3D;&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span><br><span class="line">    p:defaultEncoding&#x3D;&quot;UTF-8&quot;</span><br><span class="line">    p:maxUploadSize&#x3D;&quot;5400000&quot;</span><br><span class="line">    p:uploadTempDir&#x3D;&quot;fileUpload&#x2F;temp&quot;</span><br><span class="line">   &gt; </span><br><span class="line">&lt;&#x2F;beans:bean&gt; </span><br></pre></td></tr></table></figure>

<p>其中属性详解：<br>defaultEncoding=”UTF-8” 是请求的编码格式，默认为iso-8859-1<br>maxUploadSize=”5400000” 是上传文件的大小，单位为字节<br>uploadTempDir=”fileUpload/temp” 为上传文件的临时路径</p>
<h3 id="2-案例"><a href="#2-案例" class="headerlink" title="2. 案例"></a>2. 案例</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt; </span><br><span class="line">&lt;h2&gt;文件上传实例&lt;&#x2F;h2&gt; </span><br><span class="line"></span><br><span class="line">&lt;form action&#x3D;&quot;fileUpload.html&quot; method&#x3D;&quot;post&quot; enctype&#x3D;&quot;multipart&#x2F;form-data&quot;&gt; </span><br><span class="line">  选择文件:&lt;input type&#x3D;&quot;file&quot; name&#x3D;&quot;file&quot;&gt; </span><br><span class="line">  &lt;input type&#x3D;&quot;submit&quot; value&#x3D;&quot;提交&quot;&gt;  </span><br><span class="line">&lt;&#x2F;form&gt; </span><br><span class="line"></span><br><span class="line">&lt;&#x2F;body&gt; </span><br></pre></td></tr></table></figure>

<p>注意要在form标签中加上enctype=”multipart/form-data”表示该表单是要处理文件的,这是最基本的东西，很多人会忘记然而当上传出错后则去找程序的错误，却忘了这一点。</p>
<h3 id="3-编写上传控制类"><a href="#3-编写上传控制类" class="headerlink" title="3. 编写上传控制类"></a>3. 编写上传控制类</h3><ol>
<li><p>创建一个控制类: FileUploadController和一个返回结果的页面list.jsp</p>
</li>
<li><p>编写提交表单的action</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;通过Spring的autowired注解获取spring默认配置的request </span><br><span class="line">  @Autowired</span><br><span class="line">  private HttpServletRequest request; </span><br><span class="line"></span><br><span class="line">  &#x2F;*** </span><br><span class="line">   * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile </span><br><span class="line">   * </span><br><span class="line">   * @param file </span><br><span class="line">   * @return </span><br><span class="line">   *&#x2F;</span><br><span class="line">  @RequestMapping(&quot;fileUpload&quot;) </span><br><span class="line">  public String fileUpload(@RequestParam(&quot;file&quot;) MultipartFile file) &#123; </span><br><span class="line">    &#x2F;&#x2F; 判断文件是否为空 </span><br><span class="line">    if (!file.isEmpty()) &#123; </span><br><span class="line">      try &#123; </span><br><span class="line">        &#x2F;&#x2F; 文件保存路径 </span><br><span class="line">        String filePath &#x3D; request.getSession().getServletContext().getRealPath(&quot;&#x2F;&quot;) + &quot;upload&#x2F;&quot;</span><br><span class="line">            + file.getOriginalFilename(); </span><br><span class="line">        &#x2F;&#x2F; 转存文件 </span><br><span class="line">        file.transferTo(new File(filePath)); </span><br><span class="line">      &#125; catch (Exception e) &#123; </span><br><span class="line">        e.printStackTrace(); </span><br><span class="line">      &#125; </span><br><span class="line">    &#125; </span><br><span class="line">    &#x2F;&#x2F; 重定向 </span><br><span class="line">    return &quot;redirect:&#x2F;list.html&quot;; </span><br><span class="line">  &#125; </span><br><span class="line"></span><br><span class="line">  &#x2F;*** </span><br><span class="line">   * 读取上传文件中得所有文件并返回 </span><br><span class="line">   * </span><br><span class="line">   * @return </span><br><span class="line">   *&#x2F;</span><br><span class="line">  @RequestMapping(&quot;list&quot;) </span><br><span class="line">  public ModelAndView list() &#123; </span><br><span class="line">    String filePath &#x3D; request.getSession().getServletContext().getRealPath(&quot;&#x2F;&quot;) + &quot;upload&#x2F;&quot;; </span><br><span class="line">    ModelAndView mav &#x3D; new ModelAndView(&quot;list&quot;); </span><br><span class="line">    File uploadDest &#x3D; new File(filePath); </span><br><span class="line">    String[] fileNames &#x3D; uploadDest.list(); </span><br><span class="line">    for (int i &#x3D; 0; i &lt; fileNames.length; i++) &#123; </span><br><span class="line">      &#x2F;&#x2F;打印出文件名 </span><br><span class="line">      System.out.println(fileNames[i]); </span><br><span class="line">    &#125; </span><br><span class="line">    return mav; </span><br><span class="line">  &#125; </span><br></pre></td></tr></table></figure>
</li>
<li><p>使用SpringMVC注解RequestParam来指定表单中的file参数；</p>
</li>
<li><p>指定一个用于保存文件的web项目路径</p>
</li>
<li><p>通过MultipartFile的transferTo(File dest)这个方法来转存文件到指定的路径。</p>
</li>
</ol>
<p>到此基本的文件上传就结束了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">MultipartFile类常用的一些方法：</span><br><span class="line"></span><br><span class="line">String getContentType()&#x2F;&#x2F;获取文件MIME类型</span><br><span class="line">InputStream getInputStream()&#x2F;&#x2F;后去文件流</span><br><span class="line">String getName() &#x2F;&#x2F;获取表单中文件组件的名字</span><br><span class="line">String getOriginalFilename() &#x2F;&#x2F;获取上传文件的原名</span><br><span class="line">long getSize() &#x2F;&#x2F;获取文件的字节大小，单位byte</span><br><span class="line">boolean isEmpty() &#x2F;&#x2F;是否为空</span><br><span class="line">void transferTo(File dest) &#x2F;&#x2F;保存到一个目标文件中。</span><br></pre></td></tr></table></figure>

<h3 id="4-多文件上传"><a href="#4-多文件上传" class="headerlink" title="4. 多文件上传###"></a>4. 多文件上传###</h3><p>多文件上传其实很简单，和上传其他相同的参数如checkbox一样，表单中使用相同的名称，然后action中将MultipartFile参数类定义为数组就可以。<br>接下来实现：</p>
<ol>
<li><p>创建一个上传多文件的表单：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt; </span><br><span class="line">  &lt;h2&gt;上传多个文件 实例&lt;&#x2F;h2&gt; </span><br><span class="line">  &lt;form action&#x3D;&quot;filesUpload.html&quot; method&#x3D;&quot;post&quot;</span><br><span class="line">    enctype&#x3D;&quot;multipart&#x2F;form-data&quot;&gt; </span><br><span class="line">    &lt;p&gt; </span><br><span class="line">      选择文件:&lt;input type&#x3D;&quot;file&quot; name&#x3D;&quot;files&quot;&gt; </span><br><span class="line">    &lt;p&gt; </span><br><span class="line">      选择文件:&lt;input type&#x3D;&quot;file&quot; name&#x3D;&quot;files&quot;&gt; </span><br><span class="line">    &lt;p&gt; </span><br><span class="line">      选择文件:&lt;input type&#x3D;&quot;file&quot; name&#x3D;&quot;files&quot;&gt; </span><br><span class="line">    &lt;p&gt; </span><br><span class="line">      &lt;input type&#x3D;&quot;submit&quot; value&#x3D;&quot;提交&quot;&gt; </span><br><span class="line">  &lt;&#x2F;form&gt; </span><br><span class="line">&lt;&#x2F;body&gt; </span><br></pre></td></tr></table></figure>
</li>
<li><p>编写处理表单的action，将原来保存文件的方法单独写一个方法出来方便共用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;*** </span><br><span class="line">   * 保存文件 </span><br><span class="line">   * @param file </span><br><span class="line">   * @return </span><br><span class="line">   *&#x2F;</span><br><span class="line">  private boolean saveFile(MultipartFile file) &#123; </span><br><span class="line">    &#x2F;&#x2F; 判断文件是否为空 </span><br><span class="line">    if (!file.isEmpty()) &#123; </span><br><span class="line">      try &#123; </span><br><span class="line">        &#x2F;&#x2F; 文件保存路径 </span><br><span class="line">        String filePath &#x3D; request.getSession().getServletContext().getRealPath(&quot;&#x2F;&quot;) + &quot;upload&#x2F;&quot;</span><br><span class="line">            + file.getOriginalFilename(); </span><br><span class="line">        &#x2F;&#x2F; 转存文件 </span><br><span class="line">        file.transferTo(new File(filePath)); </span><br><span class="line">        return true; </span><br><span class="line">      &#125; catch (Exception e) &#123; </span><br><span class="line">        e.printStackTrace(); </span><br><span class="line">      &#125; </span><br><span class="line">    &#125; </span><br><span class="line">    return false; </span><br><span class="line">  &#125; </span><br></pre></td></tr></table></figure>
</li>
<li><p>编写action:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(&quot;filesUpload&quot;) </span><br><span class="line">public String filesUpload(@RequestParam(&quot;files&quot;) MultipartFile[] files) &#123; </span><br><span class="line">  &#x2F;&#x2F;判断file数组不能为空并且长度大于0 </span><br><span class="line">  if(files!&#x3D;null&amp;&amp;files.length&gt;0)&#123; </span><br><span class="line">    &#x2F;&#x2F;循环获取file数组中得文件 </span><br><span class="line">    for(int i &#x3D; 0;i&lt;files.length;i++)&#123; </span><br><span class="line">      MultipartFile file &#x3D; files[i]; </span><br><span class="line">      &#x2F;&#x2F;保存文件 </span><br><span class="line">      saveFile(file); </span><br><span class="line">    &#125; </span><br><span class="line">  &#125; </span><br><span class="line">  &#x2F;&#x2F; 重定向 </span><br><span class="line">  return &quot;redirect:&#x2F;list.html&quot;; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-原作者"><a href="#5-原作者" class="headerlink" title="5. 原作者"></a>5. 原作者</h3></li>
</ol>
<p><a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.jianshu.com/p/9ee4cb347d91">https://www.jianshu.com/p/9ee4cb347d91</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined" rel="external nofollow noreferrer">伊长空</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yichangkong.gitee.io/2019/10/22/MultipartFile/">https://yichangkong.gitee.io/2019/10/22/MultipartFile/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yichangkong.gitee.io" target="_blank">YiChangKong For Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%8A%80%E6%9C%AF/">技术</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2019/11/04/%E6%B3%A8%E8%A7%A3Service%EF%BC%88Spring%20MVC)/"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">注解Service（Spring MVC）</div></div></a></div><div class="next-post pull-right"><a href="/2019/09/02/UnsupportedOperationException/"><img class="next-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">UnsupportedOperationException</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/02/04/CSS Position/" title="CSS Position"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201122214355.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-02-04</div><div class="title">CSS Position</div></div></a></div><div><a href="/2019/07/04/Algorithm Complexity/" title="Algorithm Complexity"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201123113616.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-07-04</div><div class="title">Algorithm Complexity</div></div></a></div><div><a href="/2020/09/04/Flutter 环境搭建之过五关斩六将/" title="Flutter 环境搭建之过五关斩六将"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-04</div><div class="title">Flutter 环境搭建之过五关斩六将</div></div></a></div><div><a href="/2019/08/06/Spring MVC Overview/" title="Spring MVC Overview"><img class="cover" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201122203415.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-08-06</div><div class="title">Spring MVC Overview</div></div></a></div><div><a href="/2019/08/03/Tomcat报错/" title="Tomcat报错"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-08-03</div><div class="title">Tomcat报错</div></div></a></div><div><a href="/2020/03/11/Stack/" title="Stack"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-03-11</div><div class="title">Stack</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside_content" id="aside_content"><div class="card-widget card-info"><div class="card-content"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20200417183933.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">伊长空</div><div class="author-info__description">空气越稀薄 、风景越广阔</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">45</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">9</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">45</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/CodeSnakes"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yichangkong" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:changkongyi@gmail.com" rel="external nofollow noreferrer" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div></div><div class="card-widget card-announcement"><div class="card-content"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">繁华落尽一场空 ：风往尘香花已尽 <br> 		<div class="is-center"> 欢迎访问 <br> <a class="bookmark button--primary" id="bookmark-it" href="https://jq.qq.com/?_wv=1027&amp;k=rCby8DjL" rel="external nofollow noreferrer" title="" target="_self"><i aria-hidden="true"> </i><span>Join QQ Group 👍</span></a></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="card-content"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#MultipartFile%E7%B1%BB%EF%BC%88Spring%E6%A1%86%E6%9E%B6%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">MultipartFile类（Spring框架）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">2.</span> <span class="toc-text">1. 配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E6%A1%88%E4%BE%8B"><span class="toc-number">3.</span> <span class="toc-text">2. 案例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E7%BC%96%E5%86%99%E4%B8%8A%E4%BC%A0%E6%8E%A7%E5%88%B6%E7%B1%BB"><span class="toc-number">4.</span> <span class="toc-text">3. 编写上传控制类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%A4%9A%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="toc-number">5.</span> <span class="toc-text">4. 多文件上传###</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E5%8E%9F%E4%BD%9C%E8%80%85"><span class="toc-number">6.</span> <span class="toc-text">5. 原作者</span></a></li></ol></div></div></div><div class="card-widget card-recent-post"><div class="card-content"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/04/28/JOIN-Clause/" title="JOIN_Clause"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JOIN_Clause"/></a><div class="content"><a class="title" href="/2022/04/28/JOIN-Clause/" title="JOIN_Clause">JOIN_Clause</a><time datetime="2022-04-28T15:42:04.000Z" title="发表于 2022-04-28 23:42:04">2022-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/24/Vim%E9%94%AE%E4%BD%8D%E5%9B%BE/" title="Vim键位图"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/vi-vim-cheat-sheet-sch.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vim键位图"/></a><div class="content"><a class="title" href="/2022/03/24/Vim%E9%94%AE%E4%BD%8D%E5%9B%BE/" title="Vim键位图">Vim键位图</a><time datetime="2022-03-24T03:32:15.000Z" title="发表于 2022-03-24 11:32:15">2022-03-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/12/requirejs%20Overview/" title="RequireJs Overview"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="RequireJs Overview"/></a><div class="content"><a class="title" href="/2021/01/12/requirejs%20Overview/" title="RequireJs Overview">RequireJs Overview</a><time datetime="2021-01-12T02:43:34.000Z" title="发表于 2021-01-12 10:43:34">2021-01-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/12/12/SSM%E6%9E%B6%E6%9E%84%E4%B8%8B%E7%9A%84Cors%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" title="SSM架构下的Cors跨域问题"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201213132701.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SSM架构下的Cors跨域问题"/></a><div class="content"><a class="title" href="/2020/12/12/SSM%E6%9E%B6%E6%9E%84%E4%B8%8B%E7%9A%84Cors%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" title="SSM架构下的Cors跨域问题">SSM架构下的Cors跨域问题</a><time datetime="2020-12-12T13:13:28.000Z" title="发表于 2020-12-12 21:13:28">2020-12-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2020/11/25/DataTable/" title="DataTable"><img src="https://gitee.com/yichangkong/FigureBed/raw/master/img/20201125100521.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="DataTable"/></a><div class="content"><a class="title" href="/2020/11/25/DataTable/" title="DataTable">DataTable</a><time datetime="2020-11-25T01:45:41.000Z" title="发表于 2020-11-25 09:45:41">2020-11-25</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By 伊长空</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    let initData = {
      el: '#vcomment',
      appId: 'xuXblFdHlR0fcnQsdkLwkqvG-gzGzoHsz',
      appKey: 'ac3XS1leXcL95PWUhYV6gx0E',
      placeholder: 'Please leave your footprints',
      avatar: 'retro',
      meta: 'nick,mail'.split(','),
      pageSize: '10',
      lang: 'en',
      recordIP: false,
      serverURLs: '',
      emojiCDN: 'https://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/',
      emojiMaps: {"tv_doge":"6ea59c827c414b4a2955fe79e0f6fd3dcd515e24.png","tv_亲亲":"a8111ad55953ef5e3be3327ef94eb4a39d535d06.png","tv_偷笑":"bb690d4107620f1c15cff29509db529a73aee261.png","tv_再见":"180129b8ea851044ce71caf55cc8ce44bd4a4fc8.png","tv_冷漠":"b9cbc755c2b3ee43be07ca13de84e5b699a3f101.png","tv_发怒":"34ba3cd204d5b05fec70ce08fa9fa0dd612409ff.png","tv_发财":"34db290afd2963723c6eb3c4560667db7253a21a.png","tv_可爱":"9e55fd9b500ac4b96613539f1ce2f9499e314ed9.png","tv_吐血":"09dd16a7aa59b77baa1155d47484409624470c77.png","tv_呆":"fe1179ebaa191569b0d31cecafe7a2cd1c951c9d.png","tv_呕吐":"9f996894a39e282ccf5e66856af49483f81870f3.png","tv_困":"241ee304e44c0af029adceb294399391e4737ef2.png","tv_坏笑":"1f0b87f731a671079842116e0991c91c2c88645a.png","tv_大佬":"093c1e2c490161aca397afc45573c877cdead616.png","tv_大哭":"23269aeb35f99daee28dda129676f6e9ea87934f.png","tv_委屈":"d04dba7b5465779e9755d2ab6f0a897b9b33bb77.png","tv_害羞":"a37683fb5642fa3ddfc7f4e5525fd13e42a2bdb1.png","tv_尴尬":"7cfa62dafc59798a3d3fb262d421eeeff166cfa4.png","tv_微笑":"70dc5c7b56f93eb61bddba11e28fb1d18fddcd4c.png","tv_思考":"90cf159733e558137ed20aa04d09964436f618a1.png","tv_惊吓":"0d15c7e2ee58e935adc6a7193ee042388adc22af.png"},
      enableQQ: false,
      path: window.location.pathname,
    }

    if (true) { 
      initData.requiredFields= ('nick'.split(','))
    }
    
    if (false) {
      const otherData = false
      initData = Object.assign({}, initData, otherData)
    }
    
    const valine = new Valine(initData)
  }

  if (typeof Valine === 'function') initValine() 
  else $.getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js', initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.querySelector('#vcomment'),loadValine)
  else setTimeout(() => loadValine(), 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="https://cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script></div></body></html>